#include "iworld_manager.h"
#include "fileio/fileio.h"
#include "G.h"
#include "debug/logger.h"

namespace renderit
{
	namespace messiah
	{
		bool iworld_manager::load_worlds(const std::string& dir, std::function<void(int)> on_completed)
		{
			dir_ = dir;			
			
			std::vector<std::string> iworld_fpaths;
			std::vector<std::string> iworld_names = fileio::list_dir(dir_);
			for (auto& iworld_name : iworld_names)
			{
				std::string path = fileio::join(dir_, iworld_name);
				if (fileio::is_directory(path))
				{
					continue;
				}
				iworld_fpaths.push_back(fileio::join(dir_, iworld_name));
			}

			return load_worlds(iworld_fpaths, on_completed);
		}

		bool iworld_manager::load_worlds(const std::vector<std::string>& world_fpaths, std::function<void(int)> on_completed)
		{
			callback_ = on_completed;

			for (auto& p : world_fpaths)
			{
				if (strutil::str_endswith(p, ".iworld"))
				{
					iworld_loaders_.push_back(new iworld_loader(p));
				}
			}

			loading_count_ = iworld_loaders_.size();

			for (auto& loader : iworld_loaders_)
			{
				G->thread_worker()->dispatch([this, loader]() {
					loader->load();
					G->thread_object()->dispatch([this, loader]() {
						on_loaded(loader);
					});
				});
			}
			return true;
		}

		void iworld_manager::on_loaded(iworld_loader * loader)
		{
			loading_count_--;
		//	logger::info("Loaded iWorld(%s), Left:%d", loader->name_.c_str(), loading_count_);

			if (loading_count_ == 0 && callback_)
			{
				callback_(iworld_loaders_.size());
			}
		}

		void iworld_manager::save()
		{
			for (auto& loader : iworld_loaders_)
			{
				loader->save();
			}
		}

		uint32 iworld_manager::replace_guid(const std::string& from_guid, const std::string& to_guid)
		{
			uint32 count = 0;
			for (auto& loader : iworld_loaders_)
			{
				count += loader->replace_guid(from_guid, to_guid);
			}
			return count;
		}
	}
}